<template>
  <a-button @click="state.open=true"><user-add-outlined/>加入团队</a-button>
  <a-modal v-model:open="state.open" :footer="false" title="申请加入团队/企业">
    <div class="margin-bottom">
      <a-input-search v-model:value="state.teamName" @search="onSearch" placeholder="请输入团队名称" />
    </div>
    <div class="team-list" v-if="teamList">
      <div class="team-list-item" v-for="item in teamList">
        <a-space>
          <a-avatar :src="item.avatar"/><span>{{item.name}}</span>
        </a-space>
        <a-button @click="onInvite(item.id)" :loading="state.joinLoading"><user-add-outlined/>加入</a-button>
      </div>
    </div>
    <a-empty v-else :image="simpleImage" description="请输入关键字搜索，若没有找到可以尝试创建团队"/>
  </a-modal>
</template>
<script setup lang="ts">
import {UserAddOutlined} from "@ant-design/icons-vue";
import {reactive,ref} from "vue";
import useMessage from "@/plugin/useMessage";
import {inviteEnterprise, searchEnterprise} from "@/api/modules/enterprise";
import {getUserId} from "@/plugin/auth";
import {Empty} from 'ant-design-vue'
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

const state = reactive({
  open:false,
  teamName:'',
  listLoading:false,
  joinLoading:false,
})
const inviteForm = reactive({
  user_id: getUserId()||undefined,
  team_id:'',
})
const teamList = ref<TeamType[]>()
const onSearch = ()=>{
  if(state.teamName === ''){
    return useMessage(403,'请输入团队名称搜索');
  }
  searchEnterprise({name:state.teamName}).then(res=>{
    state.listLoading = true
    if(res.code === 200){
      teamList.value = res.data
    }else{
      useMessage(res.code,res.message)
    }
  }).finally(()=>{
    state.listLoading = false
  })
}
const onInvite = async (id:number)=>{
  inviteForm.team_id = id
  state.joinLoading = true
  setTimeout(()=>{state.joinLoading = false},3000)

  let res = await inviteEnterprise(inviteForm)
  if(res.code === 200){
    state.open = false
  }
  useMessage(res.code,res.message)
}
</script>

<style scoped>
.team-list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-radius: var(--radius);
  border: 1px solid #f5f5f5;
}
.team-list-item+.team-list-item{
  margin-top: 8px;
}
.team-list-item:hover{
  background-color: #f5f5f5;
  transition: var(--transition);
  color: var(--color-primary);
}
</style>